package com.cbw.blog.controller;


import com.cbw.blog.ResponseData.ArticleResponseData;
import com.cbw.blog.entity.Comment;

import com.cbw.blog.service.ICommentService;
import com.cbw.blog.utils.MyUtils;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-09-05
 */
@Slf4j
@Controller
@RequestMapping("/comments")
public class CommentController {

    @Autowired
    ICommentService commentService;



    @ResponseBody
    @PostMapping("/publish")
    public ArticleResponseData puvlishComment(HttpServletRequest request,
                                              @RequestParam("aid")Integer aid,
                                              @RequestParam("text")String text){
        text= MyUtils.cleanXSS(text);
        text= EmojiParser.parseToAliases(text);
       User user= (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Comment comment = new Comment();
        comment.setArticleId(aid);
        comment.setIp(request.getRemoteAddr());
        comment.setCreated(new Date());
        comment.setAuthor(user.getUsername());
        comment.setContent(text);
        try {
            commentService.pushComment(comment);
            return ArticleResponseData.ok();
        } catch (Exception e){
            log.info("发布评论失败，对应文章ID:{};错误描述{}",aid,e.getMessage());
            return  ArticleResponseData.fail();
        }

    }


}
